using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace TeamCityConfigurationMonitor.Core
{
    static class FileSystem
    {
        public static void DeleteDirectory(string directory)
        {
            if (!Directory.Exists(directory))
                return;

            foreach (var file in Directory.GetFiles(directory))
                DeleteFile(file);

            foreach (var child in Directory.GetDirectories(directory))
                DeleteDirectory(child);

            Directory.Delete(directory);
        }

        public static void DeleteFile(string file)
        {
            File.SetAttributes(file, FileAttributes.Normal);
            File.Delete(file);
        }

        public static IEnumerable<string> FindAllEmptyDirectoriesUnder(string directory)
        {
            if(!Directory.Exists(directory))
                throw new DirectoryNotFoundException(string.Format("Directory {0} could not be found", directory));

            return Directory.GetDirectories(directory, "*.*", SearchOption.AllDirectories).Where(IsEmpty);
        }

        public static bool IsEmpty(string directory)
        {
            return Directory.GetFileSystemEntries(directory).Count() == 0;
        }
    }
}